<template>
  <div>
    <el-form
      label-width="100px"
      :model="skuForm"
    >
      <el-form-item label="SPU名称">
        {{spu.spuName}}
      </el-form-item>

      <el-form-item label="SKU名称">
        <el-input
          placeholder="SKU名称"
          v-model="skuForm.skuName"
        ></el-input>
      </el-form-item>

      <el-form-item label="价格(元)">
        <el-input
          placeholder="价格(元)"
          type="number"
          v-model="skuForm.price"
        ></el-input>
      </el-form-item>

      <el-form-item label="重量(千克)">
        <el-input
          placeholder="重量(千克)"
          type="number"
          v-model="skuForm.weight"
        ></el-input>
      </el-form-item>

      <el-form-item label="规格描述">
        <el-input
          placeholder="规格描述"
          rows="4"
          type="textarea"
          v-model="skuForm.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form
          :inline="true"
          label-width="100px"
        >
          <el-form-item
            :label="attr.attrName"
            v-for="(attr) in attrList"
            :key="attr.id"
          >
            <el-select
              v-model="attr.attrIdValueId"
              placeholder="请选择"
            >
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue) in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form
          :inline="true"
          label-width="100px"
        >
          <el-form-item
            :label="spuSaleAttr.saleAttrName"
            v-for="(spuSaleAttr) in spuSaleAttrList"
            :key="spuSaleAttr.id"
          >
            <el-select
              v-model="spuSaleAttr.attrIdValueId"
              placeholder="请选择"
            >
              <el-option
                :label="spuSaleAttrValue.saleAttrValueName"
                :value="`${spuSaleAttr.id}:${spuSaleAttrValue.id}`"
                v-for="(spuSaleAttrValue) in spuSaleAttr.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table
          :data="spuImageList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="图片"
            width="width"
          >
            <template slot-scope="{row}">
              <img
                :src="row.imgUrl"
                style="width:80px"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="imgName"
            label="名称"
            width="width"
          >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width"
          >
            <template slot-scope="{row}">
              <el-button
                type="primary"
                size="mini"
                v-if="row.isDefault === '0'"
                @click="changeDefault(row,spuImageList)"
              >设为默认</el-button>
              <el-tag
                type="success"
                v-else
              >默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="save"
        >保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SkuList",
  data() {
    return {
      spu: {},
      attrList: [],
      spuSaleAttrList: [],
      spuImageList: [], //这个数组是spu的所有的图片列表
      skuImageList: [],
      skuForm: {
        // 父组件给传递的
        skuId: "",
        category3Id: "",
        tmId: "",

        // v-model直接收集
        price: "",
        skuName: "",
        weight: "string",
        skuDesc: "",

        // 通过自己写代码收集的
        skuDefaulImg: "",

        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "string",
          //   id: 0,
          //   skuId:0
          //   valueId: 0,
          //   valueName: "string",
          // },
        ],
        skuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   isDefault: "string",
          //   skuId: 0,
          //   spuImgId: 0,
          // },
        ],
        skuSaleAttrValueList: [
          // {
          //   id: 0,
          //   saleAttrId: 0,
          //   saleAttrName: "string",
          //   saleAttrValueId: 0,
          //   saleAttrValueName: "string",
          //   skuId: 0,
          //   spuId: 0,
          // },
        ],
      },
    };
  },
  // props:['visible']
  methods: {
    async getInitAddSkuFormData(row, category1Id, category2Id) {
      // Promise.all 是个方法
      // 功能:并发处理多个promise
      // 参数 数组 promise对象的数组
      // 返回值 如果成功 (数组中所有的promise都成功)所有的结果组成的数组
      //        如果失败 (数组中只要有一个promise失败就失败)第一个失败的promise失败的原因
      this.spu = row;
      // 获取平台属性列表
      let promise1 = this.$API.attr.getList(
        category1Id,
        category2Id,
        row.category3Id
      );
      // 获取spu的销售属性列表
      let promise2 = this.$API.sku.getSpuSaleAttrList(row.id);
      // 获取spu图片(因为sku的图片列表是从spu的图片列表当中选择而来的)
      let promise3 = this.$API.sku.getSpuImageList(row.id);

      const result = await Promise.all([promise1, promise2, promise3]);
      this.attrList = result[0].data;
      this.spuSaleAttrList = result[1].data;
      let spuImageList = result[2].data;
      spuImageList.forEach((item) => (item.isDefault = "0"));
      this.spuImageList = spuImageList;
    },
    // 表格选中状态发生改变的回调
    handleSelectionChange(val) {
      this.skuImageList = val;
    },
    // 点击设为默认按钮(排它)
    changeDefault(row, spuImageList) {
      spuImageList.forEach((item) => (item.isDefault = "0"));
      row.isDefault = "1";
      this.skuForm.skuDefaultImg = row.imgUrl; //收集默认图片的路径
    },
    // 清空data所有的数据
    resetData() {
      // 功能:把第二个参数对象当中的东西拷贝到第一个对象当中
      // 参数:俩对象
      // 返回值 返回的是目标对象
      // assign 方法完成的相当于是浅拷贝
      Object.assign(this._data, this.$options.data());
    },
    // 保存
    async save() {
      // 获取参数数据
      let { spu, attrList, spuSaleAttrList, skuImageList, skuForm } = this;
      // 整理参数
      skuForm.skuId = spu.id;
      skuForm.category3Id = spu.category3Id;
      skuForm.tmId = spu.tmId;
      // skuId: "",
      // category3Id: "",
      // tmId: "",

      // 最终需要的图片格式
      //   id: 0,
      //   imgName: "string",
      //   imgUrl: "string",
      //   isDefault: "string",
      //   skuId: 0,
      //   spuImgId: 0,
      skuForm.skuImageList = skuImageList.map((item) => {
        return {
          imgName: item.imgName,
          imgUrl: item.imgUrl,
          isDefault: item.isDefault,
          spuImgId: item.id,
        };
      });

      // 整理平台属性值列表和销售属性值列表
      skuForm.skuAttrValueList = attrList.reduce((prev, item) => {
        if (item.attrIdValueId) {
          let [attrId, valueId] = item.attrIdValueId.split(":");
          let obj = { attrId, valueId };
          prev.push(obj);
        }
        return prev;
      }, []);

      skuForm.skuSaleAttrValueList = spuSaleAttrList.reduce((prev, item) => {
        if (item.spuSaleAttrIdValueId) {
          let [saleAttrId, saleAttrValueId] = item.spuSaleAttrIdValueId.split(
            ":"
          );
          let obj = { saleAttrId, saleAttrValueId };
          prev.push(obj);
        }
        return prev;
      }, []);
      // 发请求
      try {
        // 成功
        const result = await this.$API.sku.addUpdate(skuForm);
        if (result.code === 200 || result.code === 20000) {
          this.$message.success("保存sku成功");
          this.$emit("update:visible", false);
          // 不需要父组件重新发请求
          // 只需要把data数据清空
          this.resetData();
        } else {
          this.$messages.error("保存sku失败");
        }
      } catch (error) {
        console.log(error);
        // 失败
        this.$message.error("请求保存失败");
      }
    },

    // 取消操作
    cancel(){
      this.$emit('update:visible',false)
      this.resetData
    }
  },
};
</script>

<style>
</style>
